/*

Frequency of use: [1] 2 3 4 5 LOW 

Short:
    Flyweight creates objects as they are needed, because keeping them around is 
unnecessary. Here the Character class is a flyweight that is only used for the 
duration of the inner loop.

Long:
    Flyweight is a software design pattern. A flyweight is an object that 
minimizes memory use by sharing as much data as possible with other similar 
objects; it is a way to use objects in large numbers when a simple repeated 
representation would use an unacceptable amount of memory. The term comes from 
the boxing weight class with the same name[citation needed]. Often some parts of 
the object state can be shared and it's common to put them in external data 
structures and pass them to the flyweight objects temporarily when they are 
used.
A classic example usage of the flyweight pattern are the data structures for 
graphical representation of characters in a word processor. It might be 
desirable to have, for each character in a document, a glyph object containing 
its font outline, font metrics, and other formatting data, but this would amount 
to hundreds or thousands of bytes for each character. Instead, for every 
character there might be a reference to a flyweight glyph object shared by every 
instance of the same character in the document; only the position of each 
character (in the document and/or the page) would need to be stored internally.

In other contexts the idea of sharing identical data structures is called hash 
consing.

Information sources:
 - http://calumgrant.net/patterns/index.html
 - http://en.wikipedia.org/wiki/Flyweight_pattern
 - http://www.dofactory.com/Patterns/Patterns.aspx
*/

#include <iostream>
#include <string>
#include <algorithm>

class Character
{
	char ch;
public:
	Character(char c) : ch(c) { }
	void output() const { std::cout << ch; }
};

struct OutputChar
{
	void operator()(char ch) const
	{
		Character(ch).output();
	}
};

void hello_world(const std::string & message)
{
	std::for_each(message.begin(), message.end(), OutputChar());
}

int main()
{
	hello_world("Hello world!\n");
	return 0;
}

